from flask_records.decorators import query_by_page, query
from flask import g
from common.utils.utils import custom_marshal_pagination

GET_BY_PAGE_SQL = """
select *
from "user"
where (is_active = :is_active or :is_active is null)
  and (
            lower("user".username) like lower(:search_str_re) or
            lower("user".notes) like lower(:search_str_re) or
            lower("user".nickname) like lower(:search_str_re) or
            :search_str_re is null
    )
  and (company_id = :company_id or :company_id is null)
  and (is_delete = :is_delete or :is_delete is null) 
"""


#  :search_str_re is null
def get_by_page(page, page_size, sorted_by, sorted_by_type, search_str, **kwargs):
    sql = GET_BY_PAGE_SQL
    order_by_sql = "{} ORDER BY {} {}".format(sql, sorted_by, sorted_by_type)

    if search_str:
        # 以空格分割，搜索所有包含的
        search_str_re = '%{}%'.format(search_str)
    else:
        search_str_re = None

    if not kwargs.get("company_id"):
        kwargs["company_id"] = g.company_id

    if not kwargs.get("is_delete"):
        kwargs["is_delete"] = False

    @query_by_page(order_by_sql, page_size=page_size)
    def _get_by_pagination(
            page, search_str_re, is_active, is_delete, company_id):
        pass

    pagination = _get_by_pagination(
        page, search_str_re, **kwargs
    )
    pagination = custom_marshal_pagination(pagination)
    return pagination
